//
//  NearFoodDetailsViewController.m
//  Food
//
//  Created by dlios on 15/7/16.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "NearFoodDetailsViewController.h"
#import "StarView.h"
#import "NearFoodDetailsModel.h"
#import "KCAnnotation.h"
#import "TJViewController.h"
#import "OtherViewController.h"
@interface NearFoodDetailsViewController ()<UIScrollViewDelegate,UIActionSheetDelegate,MBProgressHUDDelegate>

@property (nonatomic, retain)UIScrollView *myScrollView;
@property (nonatomic, retain) UILabel *nameLabel;
@property (nonatomic, retain) StarView *starView;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, retain) UILabel *favoritesLabel;
@property (nonatomic, retain) UILabel *viewLabel;
@property (nonatomic, retain) NearFoodDetailsModel *model;
@property (nonatomic, retain) KCAnnotation *kcannotation;
@property (nonatomic, retain) UILabel *addressLabel;
@property (nonatomic, retain) UIActionSheet *actionSheet;
@property (nonatomic, retain) MBProgressHUD *progress;
@property (nonatomic, retain) NSString *phoneNumber;
@end

@implementation NearFoodDetailsViewController

- (void)dealloc
{
    //[super dealloc];
//    [_myScrollView release];
//    [_nameLabel release];
//    [_timeLabel release];
//    [_starView release];
//    [_favoritesLabel release];
//    [_viewLabel release];
//    [_actionSheet release];
//    [_addressLabel release];
//    [_kcannotation release];
//    [_model release];
//    [_mapView release];
//    [_geocoder release];
//    [_locationManager release];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"餐馆详情";
    [self createView];
    [self getData];
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
    }

}

- (void)createProgress
{
    self.progress = [[MBProgressHUD alloc] initWithView:self.view];
    [self.progress show:YES];
    self.progress.labelText = @"稍等";
    self.progress.detailsLabelText = @"正在加载...";
    [self.view addSubview:self.progress];
    
}

- (void)hudWasHidden:(MBProgressHUD *)hud
{
    
    [_progress removeFromSuperview];
   // [_progress release];
}


- (void)createView
{
    self.myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.myScrollView.backgroundColor = RGBCOLOR(239, 248, 237);
    self.myScrollView.delegate = self;
    self.myScrollView.contentSize = CGSizeMake(0, 620);
    [self.view addSubview:self.myScrollView];
    //[_myScrollView release];
    
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 200, 20)];
    self.nameLabel.font = [UIFont systemFontOfSize:15];
    [self.myScrollView addSubview:self.nameLabel];
   // [_nameLabel release];
    
    self.starView = [[StarView alloc] initWithFrame:CGRectMake(10, 40, 100, 20)];
    [self.myScrollView addSubview:self.starView];
    //[_starView release];
    
    UIImageView *openView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 20, 20)];
    openView.image = [UIImage imageNamed:@"iconfont-time"];
    [self.myScrollView addSubview:openView];
    
    UILabel *open_time = [[UILabel alloc] initWithFrame:CGRectMake(30, 70, 100, 20)];
    open_time.text = @"营业时间:";
    open_time.font = [UIFont systemFontOfSize:15];
    [self.myScrollView addSubview:open_time];
    //[open_time release];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 70, 150, 20)];
    self.timeLabel.font = [UIFont systemFontOfSize:15];
    [self.myScrollView addSubview:self.timeLabel];
   // [_timeLabel release];
    UIImageView *likeView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 90, 20, 20)];
    likeView.image = [UIImage imageNamed:@"iconfont-shoucang01"];
    [self.myScrollView addSubview:likeView];
    
    self.favoritesLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 90, 100, 20)];
    [self.myScrollView addSubview:self.favoritesLabel];
    self.favoritesLabel.font = [UIFont systemFontOfSize:15];
    //[_favoritesLabel release];
    UIImageView *lookView = [[UIImageView alloc] initWithFrame:CGRectMake(130, 90, 20, 20)];
    lookView.image = [UIImage imageNamed:@"iconfont-liulan"];
    [self.myScrollView addSubview:lookView];
    
    self.viewLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 90, 100, 20)];
    [self.myScrollView addSubview:self.viewLabel];
    self.viewLabel.font = [UIFont systemFontOfSize:15];
   // [_viewLabel release];
    
    UIImageView *mapImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 130, 300, 230)];
    mapImg.userInteractionEnabled = YES;
    mapImg.layer.cornerRadius = 5;
    mapImg.layer.masksToBounds = YES;
    mapImg.backgroundColor = [UIColor whiteColor];
    [self.myScrollView addSubview:mapImg];
    //[mapImg release];
    
    self.addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 205, 300, 20)];
    self.addressLabel.font = [UIFont systemFontOfSize:15];
    self.addressLabel.textAlignment = NSTextAlignmentCenter;
    [mapImg addSubview:self.addressLabel];
   // [_addressLabel release];
    
    UIImageView *telView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 380, 20, 20)];
    telView.image = [UIImage imageNamed:@"iconfont-dianhua"];
    [self.myScrollView addSubview:telView];
    
    UILabel *telLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 380, 100, 20)];
    telLabel.font = [UIFont systemFontOfSize:15];
    telLabel.text = @"联系电话:";
    [self.myScrollView addSubview:telLabel];
   // [telLabel release];
    
    UIImageView *messageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 440, 20, 20)];
    messageView.image = [UIImage imageNamed:@"iconfont-xinxi"];
    [self.myScrollView addSubview:messageView];
    
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 440, 100, 20)];
    messageLabel.font = [UIFont systemFontOfSize:15];
    messageLabel.text = @"餐馆其他信息:";
    [self.myScrollView addSubview:messageLabel];
    //[messageLabel release];
    UIImageView *recommendView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 500, 20, 20)];
    recommendView.image = [UIImage imageNamed:@"iconfont-tuijian"];
    [self.myScrollView addSubview:recommendView];
    
    UILabel *recommendLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 500, 100, 20)];
    recommendLabel.font = [UIFont systemFontOfSize:15];
    recommendLabel.text = @"网友推荐:";
    [self.myScrollView addSubview:recommendLabel];
    //[recommendLabel release];
    
    _geocoder = [[CLGeocoder alloc] init];
   
    // 创建地图
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(5, 5, 290, 190)];
    self.mapView.delegate = self;
    // 是否显示当前位置
    self.mapView.showsUserLocation = YES;
    // 标准地图
    self.mapView.mapType =  MKMapTypeStandard;
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    [mapImg addSubview:self.mapView];
    //[_mapView release];
    
    self.locationManager = [[CLLocationManager alloc] init];
    // 设置定位精度

    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        [_locationManager requestWhenInUseAuthorization];
        
    }
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        self.locationManager.delegate = self;
        CLLocationDistance distance=10.0;
        self.locationManager.distanceFilter = distance;
        // 开始定位
        [self.locationManager startUpdatingLocation];
   // [_locationManager release];
    
    
}

- (void)tel:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"拨打电话%@",self.model.phone];
    self.actionSheet = [[UIActionSheet alloc] initWithTitle:str delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拨号" otherButtonTitles:nil, nil];
    [self.actionSheet showInView:self.view];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self makeCall];
    }
    if (buttonIndex == 1) {
        NSLog(@"取消");
    }
}

#pragma mark- 拨打电话

- (void)makeCall
{
    NSLog(@"拨打电话");
    

    NSString *str = [NSString stringWithFormat:@"tel://%@",self.phoneNumber];
    NSLog(@"====%ld",str.length);
    NSURL *url = [NSURL URLWithString:str];
    [[UIApplication sharedApplication] openURL:url];

}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    userLocation.title = @"我的位置";
    CLLocationCoordinate2D center = userLocation.location.coordinate;
    
    MKCoordinateSpan span = MKCoordinateSpanMake(0.02, 0.02);//这个显示大小精度自己调整
    MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
    [_mapView setRegion:region animated:YES];
    NSLog(@"用户位置改变 lat %f, lng %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        NSLog(@"详细信息:%@",placemark.locality);
    }];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"=======%@",error);
    
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *str = @"SJF";
        MKAnnotationView *annotationView = (MKAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:str];
        if (!annotationView) {
            annotationView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:str];
            annotationView.canShowCallout  = YES;
            annotationView.leftCalloutAccessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"location"]];
        }
        annotationView.annotation = annotation;
        annotationView.image = ((KCAnnotation *)annotation).image1;
        return annotationView;
    }
    return nil;
}



- (void)getData
{
    NSString *str1 = @"http://api.meishixing.com/place/place/placedetail/place_id=";
    NSString *str2 = @"&session_id=000012b2aeca4600ed78e8f04006451605e8cc";
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",str1,self.url,str2];
    NSLog(@"=======%@",urlStr);
    self.model = [[NearFoodDetailsModel alloc] init];
   // [_model release];
    [AFNet connectNetGetDataWithURLString:urlStr parameters:nil finishblock:^(id result) {
        NSMutableDictionary *dic = [result objectForKey:@"result"];
        [self.model setValuesForKeysWithDictionary:dic];
        [self lodeView];
        [self addAnnotation];
    }];
    
}

- (void)lodeView
{
    self.nameLabel.text = self.model.place_name;
    [self.starView createViewWithScore:self.model.star];
    self.timeLabel.text = self.model.open_time;
    self.favoritesLabel.text = [NSString stringWithFormat:@"被%ld次收藏",self.model.favorites_total];
    self.viewLabel.text = [NSString stringWithFormat:@"浏览%ld次",self.model.view_total];
    self.addressLabel.text = self.model.address;
    if (![self.model.phone isEqualToString:@""]) {
        
        UILabel *tel = [[UILabel alloc] initWithFrame:CGRectMake(40, 405, 200, 30)];
        tel.font = TEXTFONT;
        tel.backgroundColor = [UIColor whiteColor];
        tel.text = [NSString stringWithFormat:@"拨打电话:%@",self.model.phone];
        NSString *str = self.model.phone;
        NSArray *arr = [str componentsSeparatedByString:@" "];
        self.phoneNumber = arr[0];

        [self.myScrollView addSubview:tel];
        //[tel release];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.frame = CGRectMake(30, 405, 200, 30 );
        [button addTarget:self action:@selector(tel:) forControlEvents:UIControlEventTouchUpInside];
        [self.myScrollView addSubview:button];
    }else
    {
        UILabel *tel = [[UILabel alloc] initWithFrame:CGRectMake(40, 405, 200, 30)];
        tel.font = TEXTFONT;
        tel.backgroundColor = [UIColor whiteColor];
        tel.text = @"暂无电话";
        [self.myScrollView addSubview:tel];
        //[tel release];
    }
    
    if (![self.model.tags isEqualToString:@""]) {
        UILabel *message = [[UILabel alloc] initWithFrame:CGRectMake(40, 465, 200, 30)];
        message.font = TEXTFONT;
        message.backgroundColor = [UIColor whiteColor];
        message.text = @"点击查看";
        [self.myScrollView addSubview:message];
       // [message release];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.frame = CGRectMake(40, 465, 200, 30 );
        [button addTarget:self action:@selector(canguan:) forControlEvents:UIControlEventTouchUpInside];
        [self.myScrollView addSubview:button];
    }else
    {
        UILabel *message = [[UILabel alloc] initWithFrame:CGRectMake(40, 465, 200, 30)];
        message.font = TEXTFONT;
        message.backgroundColor = [UIColor whiteColor];
        message.text = @"暂无信息";
        [self.myScrollView addSubview:message];
       // [message release];
        
    }
    
    if (self.model.food_list.count != 0) {
        
        UILabel *tj = [[UILabel alloc] initWithFrame:CGRectMake(40, 525, 200, 30)];
        tj.font = TEXTFONT;
        tj.backgroundColor = [UIColor whiteColor];
        tj.text = @"点击查看";
        [self.myScrollView addSubview:tj];
        //[tj release];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(40, 525, 200, 30 );
        button.backgroundColor = [UIColor clearColor];
        [button addTarget:self action:@selector(tuijian:) forControlEvents:UIControlEventTouchUpInside];
        [self.myScrollView addSubview:button];
    }else
    {
        UILabel *tj = [[UILabel alloc] initWithFrame:CGRectMake(40, 525, 200, 30)];
        tj.font = TEXTFONT;
        tj.backgroundColor = [UIColor whiteColor];
        tj.text = @"暂无推荐";
        [self.myScrollView addSubview:tj];
       // [tj release];
    }
    
}

- (void)tuijian:(UIButton *)button
{
    NSLog(@"推荐");
    TJViewController *tjVC = [[TJViewController alloc] init];
    tjVC.placeID = self.url;
    [self.navigationController pushViewController:tjVC animated:YES];
    
}

- (void)canguan:(UIButton *)button
{
    NSLog(@"餐馆信息");
    OtherViewController *other = [[OtherViewController alloc] init];
    other.str = self.model.tags;
    [self.navigationController pushViewController:other animated:YES];
}

// 大头针
- (void)addAnnotation
{
    CLLocationCoordinate2D location1;
    location1.latitude = self.model.place_geo_lat;
    location1.longitude = self.model.place_geo_lng;
    self.kcannotation = [[KCAnnotation alloc] initWithCoordinate2D:location1];
    self.kcannotation.image1 = [UIImage imageNamed:@"RedPoint"];
    self.kcannotation.title = self.model.place_name;
    [_mapView addAnnotation:self.kcannotation];
   
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
